
import re
from io import BytesIO
from docxtpl import DocxTemplate
from docx import Document


# -----------------------------
# 处理 **加粗**，暂时不处理 _斜体_ 或 ~~删除线~~
# -----------------------------
def bold_md_runs(paragraph):
    """
    遍历段落，查找被 ** 包围的文本并加粗
    """
    # 匹配 **内容**
    pattern = r'\*\*(.*?)\*\*'
    for run in paragraph.runs:
        text = run.text
        matches = list(re.finditer(pattern, text))
        if not matches:
            continue

        last_idx = 0
        new_runs = []

        for m in matches:
            start, end = m.span()

            # 前缀文本，保持原样式
            if start > last_idx:
                r = paragraph.add_run(text[last_idx:start])
                r.bold = run.bold
                r.italic = run.italic
                r.underline = run.underline
                r.font.name = run.font.name
                if run.font.size: r.font.size = run.font.size
                if run.font.color.rgb: r.font.color.rgb = run.font.color.rgb

            # 加粗文本
            r = paragraph.add_run(m.group(1))
            r.bold = True
            # 继承原样式
            r.italic = run.italic
            r.underline = run.underline
            r.font.name = run.font.name
            if run.font.size: r.font.size = run.font.size
            if run.font.color.rgb: r.font.color.rgb = run.font.color.rgb

            last_idx = end

        # 后缀文本
        if last_idx < len(text):
            r = paragraph.add_run(text[last_idx:])
            r.bold = run.bold
            r.italic = run.italic
            r.underline = run.underline
            r.font.name = run.font.name
            if run.font.size: r.font.size = run.font.size
            if run.font.color.rgb: r.font.color.rgb = run.font.color.rgb

        # 清空原 run
        run.text = ""

        # -----------------------------
        # 将来可以在这里扩展支持：
        # _斜体_ -> r.italic = True
        # ~~删除线~~ -> r.strike = True
        # -----------------------------

# -----------------------------
# 遍历文档，处理段落和表格
# -----------------------------
def process_doc(doc):
    for p in doc.paragraphs:
        bold_md_runs(p)
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for p in cell.paragraphs:
                    bold_md_runs(p)

# -----------------------------
# 渲染模板并处理 **加粗**
# -----------------------------
def render_docx(template_path: str, context) -> BytesIO:
    tpl = DocxTemplate(template_path)
    tpl.render(context)
    doc_bytes = BytesIO()
    tpl.save(doc_bytes)
    doc_bytes.seek(0)

    doc = Document(doc_bytes)
    process_doc(doc)

    final_bytes = BytesIO()
    doc.save(final_bytes)
    final_bytes.seek(0)
    return final_bytes